import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class DatagramClient {
	private final static int PACKETSIZE = 100;

	public static void main(String args[]) {
		// Validation for correct number of arguments
		if (args.length == 3) {
			if (args[2].toString().equals("push")) {
				System.out
						.println("usage for push: java DatagramClient host port push item");
				return;
			}
		} else if (args.length > 4) {
			System.out
					.println("usage: java DatagramClient host port push item");
			System.out.println("usage: java DatagramClient host port pop");
			System.out.println("usage: java DatagramClient host port print");
			return;
		}
		DatagramSocket socket = null;
		byte[] data = null;
		DatagramPacket packet = null;
		try {
			// Convert the arguments first, to ensure that they are valid
			InetAddress host = InetAddress.getByName(args[0]);
			int port = Integer.parseInt(args[1]);
			// Construct the socket
			socket = new DatagramSocket();
			// If command is push then send the command and the item to be
			// inserted into the stack
			if (args[2].toString().trim().equals("push")) {
				packet = new DatagramPacket(args[2].toString().trim()
						.getBytes(), args[2].toString().trim().length(), host,
						port);
				socket.send(packet);
				packet = new DatagramPacket(args[3].toString().trim()
						.getBytes(), args[3].toString().trim().length(), host,
						port);
				socket.send(packet);
			} else if (args[2].toString().equals("pop")) {
				// If command is pop then send the command and wait for the
				// server response
				data = args[2].trim().toString().getBytes();
				packet = new DatagramPacket(data, data.length, host, port);
			} else if (args[2].toString().equals("print")) {
				// For print command send the command and wait for the server
				// response
				data = args[2].trim().toString().getBytes();
				packet = new DatagramPacket(data, data.length, host, port);
			} else {
				System.out.println("Invalid stack operation !!");
				System.exit(-1);
			}
			// Send the packet to the server
			socket.send(packet);
			// Set a receive timeout, 2000 milliseconds
			socket.setSoTimeout(2000);
			// Prepare the packet for receive
			packet.setData(new byte[PACKETSIZE]);
			// Wait for a response from the server
			socket.receive(packet);
			// Print the response
			System.out.println("SERVER Rx: " + new String(packet.getData()));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (socket != null)
				socket.close();
		}
	}
}